package com.yance.fim.cluster.websocket;

import com.google.common.cache.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class WebSocketClientCache {

    private static Logger logger = LoggerFactory.getLogger(WebSocketClientCache.class);

    private static WebSocketClientCache webSocketClientCache = null;

    public WebSocketClientCache() {
    }

    public static WebSocketClientCache getInstance() {
        if (null == webSocketClientCache) {
            synchronized (WebSocketClientCache.class) {
                if (null == webSocketClientCache) {
                    webSocketClientCache = new WebSocketClientCache();
                }
            }
        }
        return webSocketClientCache;
    }

    private static LoadingCache<String, WebsocketClientClusterCreator> websocketClientClusterCache
            = CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.MINUTES).
            removalListener((RemovalListener<String, WebsocketClientClusterCreator>) removalNotification -> {
                String uri = removalNotification.getKey();
                WebsocketClientClusterCreator clientClusterCreator = removalNotification.getValue();
                logger.warn("ClusterClient [{}] Closeding", uri);
                if (null != clientClusterCreator) {
                    clientClusterCreator.onDestroy(false);
                }
            }).build(new CacheLoader<String, WebsocketClientClusterCreator>() {
        @Override
        public WebsocketClientClusterCreator load(String s) throws Exception {
            return null;
        }
    });

    public WebsocketClientClusterCreator getKey(String key) {
        WebsocketClientClusterCreator websocketClientClusterCreator = null;
        try {
            websocketClientClusterCreator = websocketClientClusterCache.get(key);
        } catch (Exception e) {
        }
        return websocketClientClusterCreator;
    }

    public void putCache(String key, WebsocketClientClusterCreator websocketClientClusterCreator) {
        websocketClientClusterCache.put(key, websocketClientClusterCreator);
    }

    public void deleteCache(String key){
        websocketClientClusterCache.invalidate(key);
    }
}
